/*
 * SessionManualesViaWebBean.java
 *
 * Created on August 15, 2007, 10:58 AM
 * Copyright FSanchez
 */
package consultasmanualviaweb;

import com.computec.manualesweb.constantes.ConstantesGenerales;
import com.computec.manualesweb.dto.AplicacionesComparator;
import com.computec.manualesweb.dto.AplicacionesDto;
import com.computec.manualesweb.dto.VersionDto;
import com.computec.manualesweb.exception.ManualWebException;
import com.src.computec.radar.base.ldap.dto.LdapUserDto;
import com.src.computec.radar.base.source.CoreSource;
import com.src.computec.radar.services.utilities.consultas.delegate.ConsultasDelegate;
import com.src.computec.radar.services.utilities.consultas.exception.ConsultasException;
import com.sun.rave.web.ui.appbase.AbstractSessionBean;
import com.sun.rave.web.ui.model.Option;
import com.computec.manualesweb.delegate.ManualWebDelegate;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.faces.FacesException;
import javax.faces.context.FacesContext;

/**
 * <p>Session scope data bean for your application.  Create properties
 *  here to represent cached data that should be made available across
 *  multiple HTTP requests for an individual user.</p>
 *
 * <p>An instance of this class will be created for you automatically,
 * the first time your application evaluates a value binding expression
 * or method binding expression that references a managed bean using
 * this class.</p>
 */
public class SessionManualesViaWebBean extends AbstractSessionBean {
    // <editor-fold defaultstate="collapsed" desc="Creator-managed Component Definition">
    private int __placeholder;
    private String ldapUser;
    
    private Option[] appOptions=null;
    private Option[] verOptions=null;
    private String pathFile=null;
    private File uploadedFile=null;
    private HashMap filesMap=null;
    private HashMap hashAplicaciones=null;
    private HashMap hashVersiones=null;
    private boolean renderedAlertCarga=false;
    private boolean renderedAlertConsulta=false;
    private boolean renderedModificarButton=false;
    private boolean renderedTabla=false;
    private boolean roleEmpreseaMensajeria=false;
    private boolean roleComputec=false;
    private boolean roleCliente=false;
    private boolean roleAdministrador=false;
    private ArrayList fail;
    private ArrayList listManuales;
   
    
    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
    }
    // </editor-fold>


    /** 
     * <p>Construct a new session data bean instance.</p>
     */
    public SessionManualesViaWebBean() {
	this.setLdapUser("fsanchez.computec");     
	//this.setLdapUser(this.getUIdByDomainName(FacesPortletUtil.getPortletRequest(FacesContext.getCurrentInstance()).getRemoteUser()));
	this.setLdapUser(getLdapUser());
	try{
	    this.findRolesUser();
	}catch(ConsultasException cex){
	    cex.printStackTrace();
	}
	this.filesMap=new HashMap();
	this.fail=new ArrayList();
    }

    /** 
     * <p>Return a reference to the scoped data bean.</p>
     */
    protected ApplicationManualesViaWebBean getApplicationManualesViaWebBean() {
        return (ApplicationManualesViaWebBean)getBean("ApplicationManualesViaWebBean");
    }


    /** 
     * <p>This method is called when this bean is initially added to
     * session scope.  Typically, this occurs as a result of evaluating
     * a value binding or method binding expression, which utilizes the
     * managed bean facility to instantiate this bean and store it into
     * session scope.</p>
     * 
     * <p>You may customize this method to initialize and cache data values
     * or resources that are required for the lifetime of a particular
     * user session.</p>
     */
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
	setAppOptions(this.getAplicacionesOptions());
	setVerOptions(this.getVersionesOptions());
	//listManuales=(ArrayList)this.getManualesRadar("");
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here

        // <editor-fold defaultstate="collapsed" desc="Creator-managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("SessionBean1 Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e: new FacesException(e);
        }
        // </editor-fold>
        // Perform application initialization that must complete
        // *after* managed components are initialized
        // TODO - add your own initialization code here

    }

    /** 
     * <p>This method is called when the session containing it is about to be
     * passivated.  Typically, this occurs in a distributed servlet container
     * when the session is about to be transferred to a different
     * container instance, after which the <code>activate()</code> method
     * will be called to indicate that the transfer is complete.</p>
     * 
     * <p>You may customize this method to release references to session data
     * or resources that can not be serialized with the session itself.</p>
     */
    public void passivate() {
    }

    /** 
     * <p>This method is called when the session containing it was
     * reactivated.</p>
     * 
     * <p>You may customize this method to reacquire references to session
     * data or resources that could not be serialized with the
     * session itself.</p>
     */
    public void activate() {
    }

    /** 
     * <p>This method is called when this bean is removed from
     * session scope.  Typically, this occurs as a result of
     * the session timing out or being terminated by the application.</p>
     * 
     * <p>You may customize this method to clean up resources allocated
     * during the execution of the <code>init()</code> method, or
     * at any later time during the lifetime of the application.</p>
     */
    public void destroy() {
    }
    
    private String getUIdByDomainName(String domainName) {
        String[] tokens =  domainName.split(",");
        if (tokens.length > 0) {
            String[] uIdTokens = (tokens[0]).split("=");
            if (uIdTokens.length == 2) {
                return uIdTokens[1];
            }
        }
        return "";
    }

    public String getLdapUser() {
        return ldapUser;
    }

    public void setLdapUser(String ldapUser) {
        this.ldapUser = ldapUser;
    }
    
    public void findRolesUser() throws ConsultasException {
        ConsultasDelegate consultasDelegate = new ConsultasDelegate();
	ConstantesGenerales.getInstance();
        LdapUserDto ldapUserDtoAux = new LdapUserDto();
        ldapUserDtoAux.setIdLdap(this.getLdapUser());	
	
	
        ldapUserDtoAux = consultasDelegate.getLdapUserByPrimaryKey(ldapUserDtoAux);
        
        Iterator iterRoles = ldapUserDtoAux.getRoles().iterator();	
        while(iterRoles.hasNext()) {
            String nombreRole = (String) iterRoles.next();
	    
            if (nombreRole.compareToIgnoreCase(CoreSource.getInstance().getLdapSetupKey("ldap_rol_empresa_mensajeria_cn")) == 0) {               		
		this.setRoleEmpreseaMensajeria(true);
            }else if(nombreRole.compareToIgnoreCase(CoreSource.getInstance().getLdapSetupKey("ldap_rol_cliente_cn")) == 0){
		this.setRoleCliente(true);
	    }else if(nombreRole.compareToIgnoreCase(CoreSource.getInstance().getLdapSetupKey("ldap_rol_administrador_cn")) == 0){
		this.setRoleAdministrador(true);
	    }else if(this.getLdapUser().endsWith("." + ConstantesGenerales.USUARIO_COMPUTEC) && !this.isRoleAdministrador()){
		this.setRoleComputec(true);
	    }
        }	
    }
      
      
    public Option[] getAplicacionesOptions() 
    {
        try
        {	    
            ManualWebDelegate delegate = new ManualWebDelegate();
         
            HashMap hashAplicaciones = delegate.getAplicaciones();
	    this.setHashAplicaciones(hashAplicaciones);
            Collection keyCollection_= hashAplicaciones.values();
	    ArrayList valueList=new ArrayList(keyCollection_);
	    Collections.sort(valueList,new AplicacionesComparator());
	    
            Option[] optionsAux = new Option[ valueList.size() + 1 ];            
            optionsAux[0] = new Option("","Seleccione...");     
            
            Iterator iter = valueList.iterator();
            
            for(int i = 1; iter.hasNext(); i++)
            {
		AplicacionesDto dto = (AplicacionesDto)iter.next();
                optionsAux[i] = new Option(dto.getIdApp(),dto.getAplicacion()+"-"+dto.getSubAplicacion());
            }   
            
            return optionsAux;           
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return null;
        }        
    }
    
    public Option[] getVersionesOptions() 
    {
        try
        {
	    
            ManualWebDelegate delegate = new ManualWebDelegate();
         
            HashMap hashVersiones = delegate.getVersiones();
	    this.setHashVersiones(hashVersiones);
            Collection keyCollection_= hashVersiones.values();
	    ArrayList valueList=new ArrayList(keyCollection_);
	  
	    
            Option[] optionsAux = new Option[ valueList.size() + 1 ];            
            optionsAux[0] = new Option("","Seleccione...");     
            
            Iterator iter = valueList.iterator();
            
            for(int i = 1; iter.hasNext(); i++)
            {
		VersionDto dto = (VersionDto)iter.next();
                optionsAux[i] = new Option(dto.getIdVersion(),dto.getNombreVersion());
            }   
            
            return optionsAux;           
        }
        catch(Exception e)
        {
            e.printStackTrace();
            return null;
        }        
    }
    
    
    public List getManualesRadar(String pBusqueda){
	String idVersion="";
	if(this.isRoleCliente()){
	    idVersion=ConstantesGenerales.ID_VERSION_CLIENTE;    
	}else if(this.isRoleComputec()){
	    idVersion=ConstantesGenerales.ID_VERSION_COMPUTEC;
	}else if(this.isRoleEmpreseaMensajeria()){
	    idVersion=ConstantesGenerales.ID_VERSION_EMENSAJERIA;
	}
	
	
	ManualWebDelegate delegate_=new ManualWebDelegate();
	ArrayList listMan_=null;
	try{
	    listMan_=(ArrayList)delegate_.getManualesRadar(pBusqueda.trim(), idVersion);
	}catch(ManualWebException mex){
	    mex.printStackTrace();
	}
	return listMan_;
    }

    public Option[] getAppOptions() {
        return appOptions;
    }

    public void setAppOptions(Option[] appOptions) {
        this.appOptions = appOptions;
    }

    public Option[] getVerOptions() {
        return verOptions;
    }

    public void setVerOptions(Option[] verOptions) {
        this.verOptions = verOptions;
    }

    public String getPathFile() {
        return pathFile;
    }

    public void setPathFile(String pathFile) {
        this.pathFile = pathFile;
    }

    public File getUploadedFile(String pLdapUser) {
        return (File)filesMap.get(pLdapUser);
	//return uploadedFile;
    }

    public void setUploadedFile(File uploadedFile,String pLdapUser) {
	this.filesMap.put(pLdapUser, uploadedFile);
        //this.uploadedFile = uploadedFile;
    }

    public HashMap getHashAplicaciones() {
        return hashAplicaciones;
    }

    public void setHashAplicaciones(HashMap hashAplicaciones) {
        this.hashAplicaciones = hashAplicaciones;
    }

    public HashMap getHashVersiones() {
        return hashVersiones;
    }

    public void setHashVersiones(HashMap hashVersiones) {
        this.hashVersiones = hashVersiones;
    }

    public boolean isRenderedAlert() {
        return renderedAlertCarga;
    }

    public void setRenderedAlert(boolean renderedAlert) {
        this.renderedAlertCarga = renderedAlert;
    }

    public boolean isRenderedModificarButton() {
        return renderedModificarButton;
    }

    public void setRenderedModificarButton(boolean renderedModificarButton) {
        this.renderedModificarButton = renderedModificarButton;
    }

    public ArrayList getFail() {
        return fail;
    }

    public void setFail(ArrayList fail) {
        this.fail = fail;
    }

    public ArrayList getListManuales() {
        return listManuales;
    }

    public void setListManuales(ArrayList listManuales) {
        this.listManuales = listManuales;
    }

    public boolean isRenderedTabla() {
        return renderedTabla;
    }

    public void setRenderedTabla(boolean renderedTabla) {
        this.renderedTabla = renderedTabla;
    }

    public boolean isRenderedAlertConsulta() {
        return renderedAlertConsulta;
    }

    public void setRenderedAlertConsulta(boolean renderedAlertConsulta) {
        this.renderedAlertConsulta = renderedAlertConsulta;
    }

    public boolean isRoleEmpreseaMensajeria() {
        return roleEmpreseaMensajeria;
    }

    public void setRoleEmpreseaMensajeria(boolean roleEmpreseaMensajeria) {
        this.roleEmpreseaMensajeria = roleEmpreseaMensajeria;
    }

    public boolean isRoleComputec() {
        return roleComputec;
    }

    public void setRoleComputec(boolean roleComputec) {
        this.roleComputec = roleComputec;
    }

    public boolean isRoleCliente() {
        return roleCliente;
    }

    public void setRoleCliente(boolean roleCliente) {
        this.roleCliente = roleCliente;
    }

    public boolean isRoleAdministrador() {
        return roleAdministrador;
    }

    public void setRoleAdministrador(boolean roleAdministrador) {
        this.roleAdministrador = roleAdministrador;
    }

  }
